import React, { useState } from 'react';
import { Breadcrumb } from 'antd';
import { useLocation, matchPath } from 'react-router-dom';
import type { ItemType } from 'antd/es/breadcrumb/Breadcrumb';
import { useEffect } from 'react';
import config from '@/router/index';

interface BreadItem {
    path: string;
    breadcrumb: string;
    children?: BreadItem[];
}

const flattenBreadItems = (items: BreadItem[], insterPath: string): BreadItem[] => {
    return items.reduce((current: BreadItem[], item: BreadItem) => {
        let copyItem = {
            path: insterPath + item.path + '/',
            breadcrumb: item.breadcrumb,
            children: item.children,
        };
        current.push(copyItem);
        if (item.children) {
            current.push(...flattenBreadItems(item.children, copyItem.path));
        }
        return current;
    }, []);
};

const flattened = flattenBreadItems(config as any, '');
const findMatchedBreadItems = (pathname: string): BreadItem[] => {
    return flattened.filter((item) => matchPath({ path: item.path, end: false }, pathname));
};
const AppBreadcrumb: React.FC = () => {
    const { pathname } = useLocation();

    const [breadcrumbItems, setBreadcrumbItems] = useState<ItemType[]>([]);

    useEffect(() => {
        const matchedItems = findMatchedBreadItems(pathname);
        setBreadcrumbItems(
            matchedItems.map((item) => ({
                title: item.breadcrumb,
            }))
        );
    }, [pathname]);

    return <Breadcrumb style={{ lineHeight: '64px' }} items={breadcrumbItems} />;
};

export default AppBreadcrumb;
